package com.icost.directive.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.TimeZone;

/**
 * @author zengdewu@wsyxmall.com
 * @since 2023-12-13 11:29
 */
@Slf4j
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";
    public static String YYYY_MM_DD_POINT = "yyyy.MM.dd";

    public static String YYYY_MM_DD_00_00_00 = "yyyy-MM-dd 00:00:00";
    public static String MM_DD = "MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String YYYY_MM_DD_HH = "yyyy-MM-dd HH:00:00";

    public static String YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
    public static String HH_00 = "HH:00";

    private static final String[] PARSE_PATTERNS = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    public static Date getMinTimeByDate(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    public static Date getMinHourByDate(Date date) {
        if (Objects.isNull(date)) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    public static Date getMaxTimeByDate(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    public static Date getDayAfter(Integer timestamp, int hour) {
        if (timestamp == null) {
            return null;
        }
        long milliseconds = timestamp * 1000L;
        Date originalDate = new Date(milliseconds);
        ZonedDateTime zonedDateTime = originalDate.toInstant().atZone(ZoneId.systemDefault());
        ZonedDateTime newDateTime = zonedDateTime.plusHours(hour);
        return Date.from(newDateTime.toInstant());
    }

    public static Date getDayBefore(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, days*-1);
        return calendar.getTime();
    }

    public static Date getYearBefore(Date date, int years) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, years*-1);
        return calendar.getTime();
    }

    public static Date getDayBeforeHour(Date date, int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR, hour*-1);
        return calendar.getTime();
    }

    public static Date getHoursBefore(int hours) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, hours * -1);
        return calendar.getTime();
    }
    public static Date getHoursBefore(Date date,int hours) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR, hours * -1);
        return calendar.getTime();
    }

    public static Date getMinutesBefore(int minutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, minutes * -1);
        return calendar.getTime();
    }

    public static Date getYesterday() {
        return new Date((new Date()).getTime() - 24 * 60 * 60 * 1000);
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static String parseDateToStr(final String format, final Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        return sdf.format(date);
    }

    public static String parseDateToStr(final Date date) {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date);
    }

    public static Date toDate(long second){
        if(second==0){
            return null;
        }
        return new Date(second*1000);
    }
    public static Integer toSecond(Date date){
        if(date==null){
            return 0;
        }
        return ((Long)(date.getTime()/1000)).intValue();
    }

    public static Date dateTime(final String format, final String ts) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            return sdf.parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), PARSE_PATTERNS);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static int getDateDiffHour(Date endDate, Date nowDate) {
        long nd = 1000 *  60 * 60;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        return (int) (diff / nd) + 1;
    }

    public static double getDiffHour(Date endDate, Date nowDate) {
        long nd = 1000L * 60 * 60;
        long diff = endDate.getTime() - nowDate.getTime();
        double hours = (double) diff / nd;

        BigDecimal bd = new BigDecimal(String.valueOf(hours));
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    public static int getDayInterval(String startDate, String endDate, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime start = LocalDateTime.parse(startDate, formatter);
        LocalDateTime end = LocalDateTime.parse(endDate, formatter);
        return (int) Math.abs(ChronoUnit.DAYS.between(start, end));
    }

    public static String getDayBefore(String date, int days, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime inputDate = LocalDateTime.parse(date, formatter);
        LocalDateTime resultDate = inputDate.minusDays(days);
        return resultDate.format(formatter);
    }

    public static String getYearBefore(String date, int years, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime inputDate = LocalDateTime.parse(date, formatter);
        LocalDateTime resultDate = inputDate.minusYears(years);
        return resultDate.format(formatter);
    }

    public static Date getMinHoursByDate(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }


    public static Date getMaxHoursByDate(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }


    public static String getMinMonthByDate(Date date) {


        return parseDateToStr(YYYY_MM , date);
    }





    public static boolean dateComparison(Date currentDate, Date targetDate,Integer year , Integer month, Integer day) {
        if (currentDate == null || targetDate == null) {
            throw new IllegalArgumentException("Dates cannot be null");
        }

        LocalDateTime dateTime = currentDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        if (year != null) {
            dateTime = dateTime.plusYears(year);
        }
        if (month != null) {
            dateTime = dateTime.plusMonths(month);
        }
        if (day != null) {
            dateTime = dateTime.plusDays(day);
        }
        LocalDateTime targetDateTime = targetDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        return dateTime.isBefore(targetDateTime);
    }

    /**
     * 获取当前日期前 num 周的周一 00:00:00
     */
    public static String getBeforeStartWeek(int num) {
        return LocalDate.now()
                .minusWeeks(num)
                .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                .atStartOfDay()
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 周的周日 23:59:59
     */
    public static String getBeforeEndWeek(int num) {
        return LocalDate.now()
                .minusWeeks(num)
                .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))
                .atTime(LocalTime.MAX)
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 月的第一天 00:00:00
     */
    public static String getBeforeStartMonth(int num) {
        return YearMonth.now()
                .minusMonths(num)
                .atDay(1)
                .atStartOfDay()
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 月的最后一天 23:59:59
     */
    public static String getBeforeEndMonth(int num) {
        return YearMonth.now()
                .minusMonths(num)
                .atEndOfMonth()
                .atTime(LocalTime.MAX)
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 季度的第一天 00:00:00
     */
    public static String getBeforeStartQuarter(int num) {
        YearMonth current = YearMonth.now().minusMonths(3L * num);
        int quarter = (current.getMonthValue() - 1) / 3;
        int startMonth = quarter * 3 + 1;

        return current
                .withMonth(startMonth)
                .atDay(1)
                .atStartOfDay()
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 季度的最后一天 23:59:59
     */
    public static String getBeforeEndQuarter(int num) {
        YearMonth current = YearMonth.now().minusMonths(3L * num);
        int quarter = (current.getMonthValue() - 1) / 3;
        int endMonth = quarter * 3 + 3;

        return YearMonth.of(current.getYear(), endMonth)
                .atEndOfMonth()
                .atTime(LocalTime.MAX)
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 半年度（上半年/下半年）的第一天 00:00:00
     */
    public static String getBeforeStartHalfYear(int num) {
        YearMonth current = YearMonth.now().minusMonths(6L * num);
        int half = current.getMonthValue() <= 6 ? 1 : 2;
        int startMonth = half == 1 ? 1 : 7;

        return current
                .withMonth(startMonth)
                .atDay(1)
                .atStartOfDay()
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 半年度的最后一天 23:59:59
     */
    public static String getBeforeEndHalfYear(int num) {
        YearMonth current = YearMonth.now().minusMonths(6L * num);
        int half = current.getMonthValue() <= 6 ? 1 : 2;
        int endMonth = half == 1 ? 6 : 12;

        return YearMonth.of(current.getYear(), endMonth)
                .atEndOfMonth()
                .atTime(LocalTime.MAX)
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 年的第一天 00:00:00
     */
    public static String getBeforeStartYear(int num) {
        return Year.now()
                .minusYears(num)
                .atDay(1)
                .atStartOfDay()
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前日期前 num 年的最后一天 23:59:59
     */
    public static String getBeforeEndYear(int num) {
        return Year.now()
                .minusYears(num)
                .atMonth(12)
                .atEndOfMonth()
                .atTime(LocalTime.MAX)
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }


    /**
     * 获取当前年份指定月份的第一天 00:00:00
     * @param month 1-12 (自动处理越界值)
     */
    public static String getMonthStart(Integer month) {
        int year = Year.now().getValue();
        return YearMonth.of(year, month)
                .atDay(1)
                .atStartOfDay()
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前年份指定月份的最后一天 23:59:59
     * @param month 1-12 (自动处理越界值)
     */
    public static String getMonthEnd(Integer month) {
        int year = Year.now().getValue();
        return YearMonth.of(year, month)
                .atEndOfMonth()
                .atTime(LocalTime.MAX)
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前年份指定季度的第一天 00:00:00
     * @param quarter 1-4 (自动处理越界值)
     */
    public static String getQuarterStart(Integer quarter) {
        int year = Year.now().getValue();
        int startMonth = (quarter - 1) * 3 + 1;  // 季度 → 起始月

        return YearMonth.of(year, startMonth)
                .atDay(1)
                .atStartOfDay()
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取当前年份指定季度的最后一天 23:59:59
     * @param quarter 1-4 (自动处理越界值)
     */
    public static String getQuarterEnd(Integer quarter) {
        int year = Year.now().getValue();
        int endMonth = quarter * 3;  // 季度 → 结束月

        return YearMonth.of(year, endMonth)
                .atEndOfMonth()
                .atTime(LocalTime.MAX)
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取指定年份的第一天 00:00:00
     * @param year 如 2025 (支持负数年份)
     */
    public static String getYearStart(Integer year) {
        return LocalDate.of(year, 1, 1)
                .atStartOfDay()
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 获取指定年份的最后一天 23:59:59
     * @param year 如 2025 (支持负数年份)
     */
    public static String getYearEnd(Integer year) {
        return Year.of(year)
                .atMonth(12)
                .atEndOfMonth()
                .atTime(LocalTime.MAX)
                .format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }
}
